package com.qdlc.p2p.biz.service.impl;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.dao.ExperienceDao;
import com.qdlc.p2p.dal.dao.ExperienceRuleDao;
import com.qdlc.p2p.dal.dao.NewActivityAwardLogDao;
import com.qdlc.p2p.dal.dto.Experience;
import com.qdlc.p2p.dal.dto.ExperienceRule;
import com.qdlc.p2p.dal.dto.NewActivityAwardLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;
import com.qdlc.p2p.dal.model.ExperienceModel;
import com.qdlc.p2p.dal.model.ExperienceRuleModel;

/**
 * Created by liaoxiangkai on 2015/11/19.
 */
@Service("giveUserExperienceService")
public class GiveUserExperienceServiceImpl implements BaseGiveAwardService {
    private Logger logger = Logger.getLogger(GiveUserExperienceServiceImpl.class);
    @Resource
    private ExperienceDao experienceDao;
    @Resource
    private ExperienceRuleDao experienceRuleDao;
    @Resource
    private NewActivityAwardLogDao newActivityAwardLogDao;

    /**
     * 发放体验券
     * @param baseGiveAwardModel
     * @return
     */
    @Override
    public void giveAward(BaseGiveAwardModel baseGiveAwardModel) {
        User user = baseGiveAwardModel.getUser();
        if (user == null) {
            throw new UserException("该用户不存在，体验券发放失败！");
        }

        ExperienceRule experienceRule = experienceRuleDao.find(baseGiveAwardModel.getRuleId());
        ExperienceRuleModel experienceRuleModel = new ExperienceRuleModel();
        // 体验券规则校验
        boolean checkResult = false;
        try {
            checkResult = experienceRuleModel.checkForGiveExperience(experienceRule);
        } catch (Exception e) {
            logger.info("体验券规则关闭或不存在");
            e.printStackTrace();
        }
        if (!checkResult) {
            return;
        }

        Experience experience = new Experience();
        experience.setUserId(user.getUserId());
        experience.setExperienceRuleId(experienceRule.getId());
        experience.setName(experienceRule.getName());
        experience.setAmount(experienceRule.getAmount());
        experience.setValidTime(experienceRule.getValidTime());
        experience.setStatus(ExperienceModel.EXPERIENCE_STATUS_UNUSED);
        experience.setSourceType(baseGiveAwardModel.getSourceType());
        experience.setAddTime(DateUtil.getNow());
        experience.setExpiredTime(DateUtil.rollDayStart(experience.getAddTime(), experienceRule.getValidTime()));
        try {
            experience = save(experience);
            if (experience != null) {
                //赠与活动记录
                NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog();
                newActivityAwardLog.setUser(baseGiveAwardModel.getUser());
                newActivityAwardLog.setTache(baseGiveAwardModel.getSourceType());
                newActivityAwardLog.setRuleType(baseGiveAwardModel.getRuleType());
                newActivityAwardLog.setRuleId(baseGiveAwardModel.getRuleId());
                newActivityAwardLog.setCount(1);
                newActivityAwardLog.setAddTime(DateUtil.getNow());
                newActivityAwardLogDao.save(newActivityAwardLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发放给单个用户
     * @param baseGiveAwardModel
     */
    @Override
    public void giveSingleUserAward(BaseGiveAwardModel baseGiveAwardModel) {
        Experience experience = new Experience();

        //赠送用户体验券关联体验券规则表
        ExperienceRule experienceRule = experienceRuleDao.find(baseGiveAwardModel.getRuleId());
        ExperienceRuleModel experienceRuleModel = new ExperienceRuleModel();
        // 体验券规则校验
        boolean checkResult = false;
        try {
            checkResult = experienceRuleModel.checkForGiveExperience(experienceRule);
        } catch (Exception e) {
            logger.info("体验券规则关闭或不存在");
            e.printStackTrace();
        }
        if (!checkResult) {
            return;
        }
        experience.setExperienceRuleId(experienceRule.getId());

        experience.setUserId(baseGiveAwardModel.getUser().getUserId());
        experience.setAmount(experienceRule.getAmount());
        experience.setValidTime(experienceRule.getValidTime());
        experience.setStatus(ExperienceModel.EXPERIENCE_STATUS_UNUSED);
        experience.setName(baseGiveAwardModel.getDescription());
        experience.setSourceType(baseGiveAwardModel.getSourceType());
        experience.setAddTime(DateUtil.getNow());
        experience.setExpiredTime(DateUtil.rollDayStart(DateUtil.getNow(), experienceRule.getValidTime()));
        try {
            experience = save(experience);
            if (null != experience) {
                NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog(baseGiveAwardModel.getUser(), baseGiveAwardModel.getSourceType(), experienceRule.getAmount(), BaseGiveAwardModel.RULE_TYPE_EXPERIENCE);
                newActivityAwardLogDao.save(newActivityAwardLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Experience save(Experience experience) throws Exception {

        // 更新体验券规则里的已发放名额
        int result = experienceRuleDao.updateQuotaYes(experience.getExperienceRuleId());
        if (result != 1) {
            logger.error("更新体验券已发放名额失败！名额已使用完，体验券发放失败!");
            throw new UserException("名额已使用完，体验券发放失败!");
        }
        // 保存体验券
        return experienceDao.save(experience);
    }

}
